//
//  NSString+Category.m
//  Community
//
//  Created by xtjun on 2023/7/4.
//

#import "NSString+Category.h"
#import <CommonCrypto/CommonDigest.h>

static NSString *rootCacheFinder = nil;
static NSString *imageCacheFinder = nil;
static NSString *downloadCacheFinder = nil;
static NSString *previewCacheFinder = nil;
static NSString *tempCacheFinder = nil;
static NSString *IMFileCacheFinder = nil;


@implementation NSString (category)


- (NSString *)firstChar {
    if (self.length == 0) return self;
    return [self substringToIndex:1];
}

- (NSString *)lastChar {
    if (self.length == 0) return self;
    return [self substringFromIndex:self.length - 1];
}

- (NSString *)removefirstChar {
    if([self length] > 0){
        return [self substringFromIndex:1];
    }
    return self;
}

- (NSString *)removeLastChar {
    if([self length] > 0){
        return [self substringToIndex:(self.length - 1)];// 去掉最后一个",";
    }
    return self;
}

- (NSString *)localizedString {
    return self;
}

- (instancetype)tj_cachePath {
    return  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[self lastPathComponent]];
}

- (instancetype)tj_documentsPath {
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[self lastPathComponent]];
}

- (instancetype)tj_tempPath {
    return [NSTemporaryDirectory() stringByAppendingPathComponent:[self lastPathComponent]];
}

+ (NSString *)tj_rootCacheFinder {
    if (!rootCacheFinder) {
        NSString *finderPath = @"com.Kai.cache".tj_cachePath;
        if (![[NSFileManager defaultManager] fileExistsAtPath:finderPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:finderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        rootCacheFinder = finderPath;
    }
    return rootCacheFinder;
}

+ (NSString *)tj_imageCacheFinder {
    if (!imageCacheFinder) {
        NSString *finderPath = [self tj_rootCacheFinder];
        NSString *imageFinderPath = [finderPath stringByAppendingPathComponent:@"Image"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:imageFinderPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:imageFinderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        imageCacheFinder = imageFinderPath;
    }
    
    return imageCacheFinder;
}

+ (NSString *)tj_downloadCacheFinder {
    
    if (!downloadCacheFinder) {
        NSString *finderPath = [NSString tj_rootCacheFinder];
        NSString *downloadFinderPath = [finderPath stringByAppendingPathComponent:@"Download"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:downloadFinderPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:downloadFinderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        downloadCacheFinder = downloadFinderPath;
    }
    return downloadCacheFinder;
}

+ (NSString *)tj_previewCacheFinder {
    
    if (!previewCacheFinder) {
    
        NSString *finderPath = [NSString tj_rootCacheFinder];
        NSString *previewCacheFinderPath = [finderPath stringByAppendingPathComponent:@"Preview"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:previewCacheFinderPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:previewCacheFinderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        previewCacheFinder = previewCacheFinderPath;
    }
    return previewCacheFinder;
}

+ (NSString *)tj_tempCacheFinder {
    
    if (!tempCacheFinder) {
    
        NSString *finderPath = [NSString tj_rootCacheFinder];
        NSString *tempCacheFinderPath = [finderPath stringByAppendingPathComponent:@"Temp"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:tempCacheFinderPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:tempCacheFinderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        tempCacheFinder = tempCacheFinderPath;
    }
    return tempCacheFinder;
}
 
//上传的本地文件
- (NSString *)tj_tmpCachePath {
    return [[NSString tj_tempCacheFinder] stringByAppendingPathComponent:[self lastPathComponent]];
}

- (NSString *)tj_finderPath {
    return [NSString tj_rootCacheFinder];
}

- (NSString *)tj_imageCachePath {
    return [[NSString tj_imageCacheFinder] stringByAppendingPathComponent:[self lastPathComponent]];
}

- (NSString *)tj_downloadCachePath {
    return [[NSString tj_downloadCacheFinder] stringByAppendingPathComponent:[self lastPathComponent]];
}

- (NSString *)tj_previewCachePath {
    return [[NSString tj_previewCacheFinder] stringByAppendingPathComponent:[self lastPathComponent]];
}
 
- (nonnull NSString *)replacingEmptyString {
    if (!self) return nil;
    if (![self isKindOfClass:NSString.class]) return @"";
    if ([self containsString:@" "]) return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    return self;
}


- (CGSize)getStringSizeWithWidth:(CGFloat)width fontSize:(CGFloat)fontSize {
    return  [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: UIFontMake(fontSize)} context:nil].size;
}

- (CGSize)getStringSizeWithWidth:(CGFloat)width font:(UIFont *)font {
    if (!font) return CGSizeZero;
    return  [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
}


- (NSAttributedString *)titleKernSpacing:(CGFloat)kernSpacing {
    NSMutableAttributedString *attributedString =  [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSKernAttributeName : @(kernSpacing)}];
    return attributedString;
}

- (NSAttributedString *)titleMargin:(CGFloat)magrin alignment:(NSTextAlignment)alignment {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:magrin];
    paragraphStyle.alignment = alignment;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    return attributedString;
}

- (NSAttributedString *)titleMargin:(CGFloat)magrin font:(UIFont *)font alignment:(NSTextAlignment)alignment {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSFontAttributeName: font
    }];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:magrin];
    paragraphStyle.alignment = alignment;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    return attributedString;
}

- (NSAttributedString *)titleMargin:(CGFloat)magrin paragraphSpacing:(CGFloat)paragraphSpacing alignment:(NSTextAlignment)alignment {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:magrin];
    paragraphStyle.paragraphSpacing = paragraphSpacing;
    paragraphStyle.alignment = alignment;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    return attributedString;
}

- (NSAttributedString *)titleMargin:(CGFloat)magrin paragraphSpacing:(CGFloat)paragraphSpacing firstLineHeadIndent:(CGFloat)firstLineHeadIndent alignment:(NSTextAlignment)alignment {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:magrin];
    paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
    paragraphStyle.paragraphSpacing = paragraphSpacing;
    paragraphStyle.alignment = alignment;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    return attributedString;
}

+ (NSString *)dateStringWithDateFormat:(NSDateFormatter *)dateFormat timeInterval:(NSTimeInterval)timeInterval {
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    
    if (!dateFormat) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        return  [formatter stringFromDate:date];
    }
    return  [dateFormat stringFromDate:date];
 
}

+ (float)floatWithdecimalNumber:(double)num {
    return [[self decimalNumber:num] floatValue];
}

+ (double)doubleWithdecimalNumber:(double)num {
    return [[self decimalNumber:num] doubleValue];
}

+ (NSString *)stringWithDecimalNumber:(double)num {
    return [[self decimalNumber:num] stringValue];
}

+ (NSDecimalNumber *)decimalNumber:(double)num {
    NSString *numString = [NSString stringWithFormat:@"%lf", num];
    return [NSDecimalNumber decimalNumberWithString:numString];
}

 
- (nonnull NSAttributedString *)attributedStringWithRange:(NSRange)range foregroundFont:(UIFont *)foregroundFont backgroundFont:(UIFont *)backgroundFont foregroundcolor:(nonnull UIColor *)foregroundcolor backgroundColor:(nonnull UIColor *)backgroundColor {
    
    NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSFontAttributeName: foregroundFont,
        NSForegroundColorAttributeName: foregroundcolor
    }];

    [newAttrStr addAttribute:NSFontAttributeName value:backgroundFont range:range];
    [newAttrStr addAttribute:NSForegroundColorAttributeName value:backgroundColor range:range];
    return  newAttrStr.copy;
}

- (nonnull NSAttributedString *)attributedStringWithRange:(NSRange)range rangeFont:(UIFont *)rangeFont rangeColor:(nonnull UIColor *)rangeColor font:(UIFont *)font color:(nonnull UIColor *)color {
    
    NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSFontAttributeName: font,
        NSForegroundColorAttributeName: color
    }];
    
    CGFloat foregroundFontSize = font.pointSize;
    CGFloat backgroundFontSize = rangeFont.pointSize;
    
    CGFloat maxFontSize = foregroundFontSize > backgroundFontSize ?  foregroundFontSize : backgroundFontSize;
    CGFloat minFontSize = foregroundFontSize < backgroundFontSize ?  foregroundFontSize : backgroundFontSize;

    [newAttrStr addAttribute:NSFontAttributeName value:rangeFont range:range];
    [newAttrStr addAttribute:NSForegroundColorAttributeName value:rangeColor range:range];
//    [newAttrStr addAttribute:NSBaselineOffsetAttributeName value:@(-1) range:range];
    return  newAttrStr.copy;
}

- (nonnull NSAttributedString *)attributedString:(NSRange)range rangeFont:(UIFont *)rangeFont rangeColor:(nonnull UIColor *)rangeColor font:(UIFont *)font color:(nonnull UIColor *)color {
    
    NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSFontAttributeName: font,
        NSForegroundColorAttributeName: color
    }];
    
    [newAttrStr addAttribute:NSFontAttributeName value:rangeFont range:range];
    [newAttrStr addAttribute:NSForegroundColorAttributeName value:rangeColor range:range];
    return  newAttrStr.copy;
}

- (nonnull NSMutableAttributedString *)attributedStringWithRangeString:(NSString *)rangeString rangeColor:(nonnull UIColor *)rangeColor color:(nonnull UIColor *)color {
    return  [self attributedStringWithRangeStrings:rangeString ? @[rangeString]:@[] rangeColor:rangeColor color:color];
}

- (nonnull NSMutableAttributedString *)attributedStringWithRangeStrings:(NSArray <NSString *>*)rangeStrings rangeColor:(nonnull UIColor *)rangeColor color:(nonnull UIColor *)color {
    
    NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSForegroundColorAttributeName: color
    }];
    for (NSString *rangeString in rangeStrings) {
        NSRange range = [self rangeOfString:rangeString];
        if (range.location != NSNotFound) {
            [newAttrStr addAttribute:NSForegroundColorAttributeName value:rangeColor range:range];
        }
    }
    return newAttrStr;
}

- (nonnull NSMutableAttributedString *)attributedStringWithRangeString:(NSString *)rangeString rangeColor:(nonnull UIColor *)rangeColor color:(nonnull UIColor *)color titleMargin:(CGFloat)magrin {
    if (!rangeString) return nil;
    NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{
        NSForegroundColorAttributeName: color
    }];
    [newAttrStr addAttribute:NSForegroundColorAttributeName value:rangeColor range:[self rangeOfString:rangeString]];
    
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:magrin];
    [newAttrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    
    return  newAttrStr;
    
}

- (NSString *)removeFirstLastEmptyString {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


- (NSURL *)URL
{
    if (self == nil) {
        return nil;
    }
    
//    [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+,-./:;=?@_~%#[]"]];
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))];
#pragma clang diagnostic pop
}

- (NSString *)encodeUrl {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8));
#pragma clang diagnostic pop
}

- (NSString *)decodeUrl {
    return [self stringByRemovingPercentEncoding];
}

- (BOOL)isEqualToString:(NSString *)string options:(NSStringCompareOptions)mask {
    return [self compare:string options:mask] == NSOrderedSame;
}

- (NSString *)md5 {
    
    NSString *str = self;
    
    if (!str) return @"";
    if (![str isKindOfClass:NSString.class]) {
        str = [NSString stringWithFormat:@"%@", str];
    }
    const char *cStr = [str UTF8String];
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (uint32_t)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]
            ];
 }
 
- (NSString *)firstPinYin {
    if (isEmptyString(self)) return self;
    //转成了可变字符串
    NSMutableString *pStr = [NSMutableString stringWithString:self];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pPinYin = [pStr capitalizedString];
    //获取并返回首字母
    return [pPinYin substringToIndex:1];
}


- (NSString *)sha1 {
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

@end
